import { login, getInfo, logout } from 'api/login';
import Cookies from 'js-cookie';

const user = {
  state: {
    username: '',
    email: '',
    token: Cookies.get('Admin-Token'),
    name: '',
    roles: [],
  },
  mutations: {
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_USERNAME: (state, username) => {
        state.username = username;
    },
    SET_NAME: (state, name) => {
        state.name = name;
    },
    SET_EMAIL: (state, email) => {
        state.email = email;
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles;
    },
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      return new Promise((resolve, reject) => {
        login(username, userInfo.password).then(response => {
          const data = response.data;
          Cookies.set('Admin-Token', response.data.token);
          commit('SET_TOKEN', data.token);
          commit('SET_USERNAME', username);
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.data;
          commit('SET_NAME', data.name);
          commit('SET_EMAIL', data.email);
          commit('SET_ROLES', data.roles);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 注销
    LogOut({ commit, state, rootState }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(response => {
            if(response.data.code == RESPONSE_STATUS.SUCCESS){
                commit('SET_TOKEN', '');
                commit('SET_ROLES', []);
                Cookies.remove('Admin-Token');
                resolve();
            }
            else{
                reject(response.data.message);
            }
        }).catch(error => {
            reject(error);
        });
      });
    },
  }
}

export default user;